package top.xana.acg.anime.ui.fragment

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import com.drake.brv.utils.grid
import com.drake.brv.utils.setup
import top.xana.acg.anime.BR
import top.xana.acg.anime.R
import top.xana.acg.anime.SearchSource
import top.xana.acg.anime.databinding.FragmentSearchListBinding
import top.xana.acg.anime.model.Anime
import top.xana.acg.anime.ui.page.AnimePlayerFragment
import top.xana.acg.anime.ui.page.SearchFragment
import top.xana.acg.anime.ui.viewmodel.AnimeViewModel
import top.xana.acg.anime.utils.cast
import top.xana.acg.anime.utils.navTo
import top.xana.acg.base.BaseFragment


class SearchListFragment : BaseFragment<FragmentSearchListBinding>(R.layout.fragment_search_list),
    SearchFragment.OnSearchListener {

    companion object {
        const val TAG = "SearchListFragment"

        private const val KYE_SEARCH_SOURCE = "kye_search_source"

        @JvmStatic
        fun newInstance(searchSource: SearchSource) = SearchListFragment().apply {
            arguments = Bundle().apply {
                putSerializable(KYE_SEARCH_SOURCE, searchSource)
            }
        }
    }

    private val viewModel by activityViewModels<AnimeViewModel>()

    private var searchSource = SearchSource.Bimi


    private var page: Int = 0

    override fun initArgs(bundle: Bundle?) {
        super.initArgs(bundle)
        arguments?.let {
            searchSource = it.getSerializable(KYE_SEARCH_SOURCE).cast() ?: searchSource
        }
    }

    override fun initView() {
        super.initView()
        binding.listView.grid(2).setup {
            modelId = BR.anime
            addType<Anime>(R.layout.item_hot_anime_view)
            onClick(R.id.frameAnime) {
                itemView.navTo(
                    R.id.toPagePlayer,
                    AnimePlayerFragment.createBundle(SearchSource.Bimi, getModel())
                )
            }
        }
        doSearch("")
    }

    override fun onSearch(kw: String) = doSearch(kw)

    private fun doSearch(kw: String) {
        binding.page.onRefresh {
            page = 1
            viewModel.search(searchSource, kw, page, this::addData)
        }.onLoadMore {
            viewModel.search(searchSource, kw, ++page) {
                addData(it) { it.isNotEmpty() }
            }
        }.autoRefresh()
    }

}